<?php

namespace App\Process;

use App\Model\CouponsUserModel;
use co;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\ORM\DbManager;
use Swoole\Process;

/**
 * Class RecoverCouponsProcess
 * 回收用户过期优惠券
 * @package App\Process
 */
class RecoverCouponsProcess extends AbstractProcess
{
    protected function run($arg)
    {
        //当进程启动后，会执行的回调
        Logger::getInstance()->info($this->getProcessName() . " run");
        var_dump($arg);

        go(function () {
            while (true) {
                Logger::getInstance()->info('回收用户过期优惠券 开始时间:' . date('Y-m-d H:i:s'));

                $res = DbManager::getInstance()->invoke(function ($client) {
                    $couponsUserModel = CouponsUserModel::invoke($client);
                    $couponsUserModel->update([
                        'status' => 3,
                        'update_time' => time(),
                        'recovery_time' => time(),
                    ], [
                        'status' => 1,
                        'validate_time' => [time(), '<']
                    ]);
                    return $couponsUserModel->lastQueryResult()->getAffectedRows();
                });


                if (!$res) {
                    Logger::getInstance()->info('没有过期用户优惠券 -_-:' . date('Y-m-d H:i:s'));
                } else {
                    Logger::getInstance()->info('回收过期优惠券有'. $res . ':' . date('Y-m-d H:i:s'));
                }

                Logger::getInstance()->info('回收用户过期优惠券 结束时间:' . date('Y-m-d H:i:s'));

                co::sleep(1);
            }
        });
    }

    protected function onPipeReadable(Process $process)
    {
        /*
         * 该回调可选
         * 当有主进程对子进程发送消息的时候，会触发的回调，触发后，务必使用
         * $process->read()来读取消息
         */
    }

    protected function onShutDown()
    {
        /*
         * 该回调可选
         * 当该进程退出的时候，会执行该回调
         */
    }

    protected function onException(\Throwable $throwable, ...$args)
    {
        /*
         * 该回调可选
         * 当该进程出现异常的时候，会执行该回调
         */
        echo $throwable->getMessage();
    }
}
